package com.softer.wxzj.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.softer.wxzj.common.entity.ActionResult;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.util.ShiroUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Gong Zhiyang
 * @date 2019/12/5
 */
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userName = ShiroUserUtil.getUserName();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(ShiroUserUtil.getUserName())) {
            log.info(request.getRequestURI() + "调用接口拦截验证登陆信息不存在，说明状态为未登陆！");
            ActionResult result = new ActionResult(ShiroResultEnum.EXPIRE.getCode(), MessageEnum.EXPIRE.getMsg(), "");
            String jsonObjectStr = JSONObject.toJSONString(result);
            returnJson(response, jsonObjectStr);
            return false;
        } else {
            return true;
        }
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
